package com.aso114.project.mvp.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aso114.project.R;
import com.aso114.project.base.BaseSimpleActivity;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.bean.TrueQuestionBean;
import com.aso114.project.exam.ExpositionTestActivity;
import com.aso114.project.exam.Question;
import com.aso114.project.exam.QuestionTestActivity;
import com.aso114.project.exam.Result;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.SystemBarHelper;
import com.aso114.project.util.ToastUtils;
import com.aso114.project.util.dbhelper.QuestionSqliteOpenHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 真题考试引导
 */
public class SatGuideActivity extends BaseSimpleActivity {
    @BindView(R.id.layout_title_bar_back_iv)
    ImageView layoutTitleBarBackIv;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    Intent intent;
    TrueQuestionBean mdata;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.nandu)
    TextView nandu;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.zongfen)
    TextView zongfen;
    @BindView(R.id.time)
    TextView time;
    Dialog dialog;
    public static String SQL = "select * from c1_1 order by random() limit 100";
    ArrayList<Result> results = new ArrayList<>();
    QuestionBean qdata;
    String catid = Constant.adutst;
    public static SatGuideActivity instance;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;
    @BindView(R.id.star)
    TextView star;

    @Override
    protected int getResouseId() {

        return R.layout.satguide_xml;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(this, 0);
        SystemBarHelper.setHeightAndPadding(this, titleTopLy);
        instance = this;
        layoutTitleBarTitleTv.setText("真题模考");

        mdata = (TrueQuestionBean) getIntent().getSerializableExtra("data");

        catid = getIntent().getStringExtra("catid");

        tv1.setText(mdata.getPaperTitle());
        nandu.setText("试卷难度:" + mdata.getDifficultyFactor());
        type.setText("试卷类型:历年真题");
        zongfen.setText("卷面总分:" + mdata.getScore());
        time.setText("作答时间:" + mdata.getExamDuration());


    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getBroadcast(Context context, Intent intent) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_title_bar_back_iv, R.id.layout_title_bar_title_tv, R.id.star})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_title_bar_back_iv:
                finish();
                break;
            case R.id.layout_title_bar_title_tv:

                break;
            case R.id.star:

                final View dialogview = SatGuideActivity.this.getLayoutInflater().inflate(
                        R.layout.loading_view, null);
                dialog = new Dialog(SatGuideActivity.this, R.style.dialogStyle);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                dialog.getWindow().setGravity(Gravity.CENTER);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);//设置是否可以按退回键取消
                dialog.show();


                CommentModel.getInstant().get_question_bank(LoginSP.getInstance().getUserAreaId(), mdata
                        .getPaperId(), catid, new CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {

                        dialog.cancel();
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        qdata = (QuestionBean) o;


                        System.out.println("题库大小111===" + qdata.getPaperTitle());

                        System.out.println("题库数组大小===" + qdata.getQuestionBaseList().get(0)
                                .getQuestionList().size());

                        EventBus.getDefault().postSticky(qdata);

                        if (Constant.titleTypeNum[0].equals(catid)) {
                            //行测
                            intent = new Intent(SatGuideActivity.this, QuestionTestActivity.class);
                            intent.putExtra(QuestionTestActivity.IS_EXAM, true);
                        } else {
                            //申论
                            intent = new Intent(SatGuideActivity.this, ExpositionTestActivity.class);
                        }
                        startActivity(intent);

                    }

                    @Override
                    public void onFailure(String fail) {
                        ToastUtils.showToast(SatGuideActivity.this, "获取题库失败");
                        dialog.cancel();
                    }
                });


                break;
        }
    }


    /**
     * Declare your subscribing method
     * 声明自己的订阅方法
     *
     * @param event
     */
    @Subscribe
    public void onEvent(QuestionBean event) {
        Toast.makeText(this, event.getPaperTitle(), Toast.LENGTH_SHORT).show();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            startActivity(intent);
        }
    };


    public void initgetData() {
        results.clear();

        new Thread() {
            @Override
            public void run() {
//                SQLiteDatabase database = SQLTools.opendatabase(MainActivity.this);


                SQLiteDatabase database;
                Cursor cursor = null;
                //获取assets目录下的数据库中的所有城市的openHelper
                QuestionSqliteOpenHelper op = new QuestionSqliteOpenHelper(SatGuideActivity.this);
//                ArrayList<City> cityList = new ArrayList<City>();

                try {


                    op.createDataBase();
                    database = op.getWritableDatabase();

                    cursor = database.rawQuery(SQL, null);
                    int question = cursor.getColumnIndex("question");
                    int answer = cursor.getColumnIndex("answer");
                    int item1 = cursor.getColumnIndex("item1");
                    int item2 = cursor.getColumnIndex("item2");
                    int item3 = cursor.getColumnIndex("item3");
                    int item4 = cursor.getColumnIndex("item4");
                    int explains = cursor.getColumnIndex("explains");
                    int url = cursor.getColumnIndex("url");
                    while (cursor.moveToNext()) {
                        Result r = new Result();
                        r.setQuestion(cursor.getString(question));
                        r.setAnswer(cursor.getString(answer));
                        r.setItem1(cursor.getString(item1));
                        r.setItem2(cursor.getString(item2));
                        r.setItem3(cursor.getString(item3));
                        r.setItem4(cursor.getString(item4));
                        r.setExplains(cursor.getString(explains));
                        r.setUrl(cursor.getString(url));
                        results.add(r);
                    }

                    Question.result = results;
                    handler.sendEmptyMessage(0);
                    cursor.close();
                    database.close();

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
//                    cursor.close();
                }

            }
        }.start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }
}
